package com.wiwf.model.mqtt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wiwf.bean.MqttWgDataBean;
import com.wiwf.model.mqtt.service.SaveGdtDataServer;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

/**
 * @author kehui
 */
@Service
public class GdtMqttReceiverImpl implements MessageHandler {

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        // 01 取得信息
        MqttWgDataBean mqWgData = JSONObject.parseArray(message.getPayload().toString(), MqttWgDataBean.class).get(0);

        try {
            String dateTime = SaveGdtDataServer.DATE_FORMAT.format(SaveGdtDataServer.DATE_FORMAT_P.parse(mqWgData.getTime()));
            dateTime = dateTime.substring(0,dateTime.length()-2)+"00";
            String flag = mqWgData.getFlag();

            if(mqWgData.FlagZ.equals(flag)){
                // 02 取得Body
                getPlcs(mqWgData.getBody(), dateTime);
            }
        } catch (ParseException e) {
            return;
        }
    }

    private void getPlcs(HashMap<String, JSONObject> body, String dateTime){
        // HashMap<String, JSONObject> hashMap = new HashMap<>();

        Set<String> keys = body.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String plcKey = iterator.next();
            JSONObject obj = body.get(plcKey);
            // String idx = SaveGdtDataServer.plcIdx.get(plcKey)+"";
            String idx = "0";

            Integer status = obj.getInteger("status");
            JSONObject regVal = obj.getJSONObject("REG_VAL");

            if(status == 0){
                System.out.print("异常变量：");
                System.out.print(plcKey);
                System.out.print("\t");
                System.out.println(regVal);
            } else {
                System.out.print("接受变量：");
                System.out.print(plcKey);
                System.out.print("\t");
                System.out.println(regVal);
                getPlcDatas(regVal,dateTime,idx,plcKey);
            }
        }
    }

    private void getPlcDatas(JSONObject regVal, String dateTime, String idx, String plcKey){
        // String year = dateTime.split("-")[0];

        Set<String> keys = regVal.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String blCode = iterator.next();
            String blVal = regVal.getString(blCode);
            if(blVal.length() > 64){
                blVal = blVal.substring(0,64);
            }

            System.out.println("------------ plcKey: " + plcKey + "\t blCode: " + blCode);
        }
    }

}
